;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Logistics.Send", [])
        .controller("LogisticsSendCtrl", ["$scope", "$state", "$q", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", function ($scope, $state, $q, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter) {
            $scope.handleCHJFBlur = function (e) {
                $scope.condition.soldOrgName = UserContextService.MultiInput(e.target.value);
            };

            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];

            $scope.markInfo = {
                allCheckedBill: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };

            $scope.dataList = [];

            $scope.detailInfo = {
                crucialDevice: 0,
                entranceDevice: 0
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/sendBill/export"),
                sectionParam: { ids: [] },
                allUrl: ybHttp.RequestUrl("device", "/sendBill/exportAll")
            };
            $scope.orderObj = {
                materialsList: [],
                headerInfo: {}
            };
            $scope.showDatepicker = false;
            $scope.billStateList = [];

            $scope.tableConfig = { // 送货单列表配置
                fixedWidth: 380,
                scrollWidth: 1500,
                tableCol: [
                    {
                        type: "",
                        name: "送货单号",
                        dataField: "sendOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建方",
                        dataField: "soldOrgName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "接收方",
                        dataField: "applyOrgName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "收货方",
                        dataField: "deliveryOrgName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "类型",
                        dataField: "sendTypeStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "直投供货商SAP代码",
                        dataField: "supplierSapCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "物流公司",
                        dataField: "logisticsCompany",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "物流单号",
                        dataField: "logisticsOrder",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否发货",
                        dataField: "deliveryStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否签收",
                        dataField: "signStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "入库状态",
                        dataField: "statusStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "note",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货时间",
                        dataField: "sendTimeShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "入库时间",
                        dataField: "rkDateShow",
                        width: 130,
                        isShow: $scope.isWJ ? true : false,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "签收时间",
                        dataField: "signDateShow",
                        width: 130,
                        isShow: $scope.isWJ ? true : false,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 340,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.materielTableConfig = { // 详情零件列
                scrollWidth: 1700,
                tableCol: [
                    {
                        name: "代理商采购单号",
                        width: 150,
                        dataField: "initialOrder",
                        needInput: false
                    },
                    {
                        name: "采购单号",
                        width: 150,
                        dataField: "sourceOrder",
                        needInput: false
                    },
                    {
                        name: "行号",
                        width: 80,
                        dataField: "rowNo",
                        type: "rowNo",
                        needInput: false,
                        hidden: ""
                    },
                    {
                        name: "零件编号",
                        width: 120,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "自定义零件编号",
                        width: 150,
                        dataField: "customMaterialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 120,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "数量",
                        width: 100,
                        dataField: "qty",
                        needInput: false
                    },
                    {
                        name: "已入库数量",
                        width: 100,
                        dataField: "realQty",
                        needInput: false
                    },
                    {
                        name: "已过账数量",
                        width: 100,
                        dataField: "postingNum",
                        needInput: false
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        needInput: false
                    },
                    {
                        name: "总价",
                        width: 100,
                        dataField: "totalPrice",
                        needInput: false
                    },
                    {
                        name: "零件凭证",
                        width: 100,
                        dataField: "voucherNo",
                        needInput: false
                    },
                    {
                        name: "过账错误信息",
                        width: 120,
                        dataField: "sapErrorMsg",
                        needInput: false
                    },
                    {
                        name: "钢印号",
                        width: 100,
                        dataField: "steelNo",
                    },
                    {
                        name: "备注",
                        width: 120,
                        dataField: "note",
                        needInput: false
                    }
                ]
            };

            $scope.directMaterielTableConfig = { // 送货单新增界面table配置信息
                scrollWidth: 1450,
                tableCol: [
                    {
                        name: "采购单号",
                        width: 150,
                        dataField: "sourceOrder",
                        needInput: false
                    },
                    {
                        name: "序号",
                        width: 50,
                        dataField: "rowNo",
                        needInput: false
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "自定义零件编号",
                        width: 150,
                        dataField: "customMaterialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "总数量",
                        width: 100,
                        dataField: "totalQty",
                        needInput: false
                    },
                    {
                        name: "已通知数量",
                        width: 100,
                        dataField: "informQty",
                        needInput: false
                    },
                    {
                        name: "本次送货数量",
                        width: 100,
                        dataField: "qty",
                        inputType: "qty",
                        needInput: true
                    },
                    {
                        name: "钢印号",
                        width: 100,
                        dataField: "steelNo",
                        inputType: "stealNo",
                        needInput: true
                    }
                ]
            };

            $scope.inTbConf = {
                scrollWidth: 1100,
                tableCol:
                    [
                        {
                            name: "代理商采购单号",
                            width: 150,
                            isShow: true,
                            dataField: "initialOrder",
                            needInput: false
                        },
                        {
                            name: "采购单号",
                            width: 150,
                            isShow: true,
                            dataField: "sourceOrder",
                            needInput: false
                        },
                        {
                            name: "行号",
                            width: 80,
                            isShow: true,
                            dataField: "rowNo",
                            type: "rowNo",
                            needInput: false,
                            hidden: ""
                        },
                        {
                            name: "零件编号",
                            width: 120,
                            isShow: true,
                            dataField: "materialsNo",
                            needInput: false
                        },
                        {
                            name: "自定义零件编号",
                            width: 150,
                            isShow: true,
                            dataField: "customMaterialsNo",
                            needInput: false
                        },
                        {
                            name: "零件中文名",
                            width: 120,
                            isShow: true,
                            dataField: "materialsDes",
                            needInput: false
                        },
                        {
                            name: "单位",
                            width: 80,
                            isShow: true,
                            dataField: "unit",
                            needInput: false
                        },
                        {
                            name: "数量",
                            width: 100,
                            isShow: true,
                            dataField: "qty",
                            needInput: false
                        },
                        {
                            name: "储位",
                            width: 150,
                            isShow: true,
                            dataField: "locationCode",
                            input: true,
                            inputType: "func"
                        },
                        {
                            name: "已入库数量",
                            width: 100,
                            isShow: true,
                            dataField: "realQty",
                            needInput: false
                        },
                        /* {
                            name: "本次入库数量",
                            width: 150,
                            isShow: !$scope.isZHJCH,
                            dataField: "currentAmount",
                            input: true,
                            inputType: "amount"
                        }, */
                        {
                            name: "已过账数量",
                            width: 100,
                            isShow: true,
                            dataField: "postingNum",
                            needInput: false
                        },
                        {
                            name: "单价",
                            width: 100,
                            dataField: "price",
                            needInput: false
                        },
                        {
                            name: "总价",
                            width: 100,
                            isShow: true,
                            dataField: "totalPrice",
                            needInput: false
                        },
                        {
                            name: "零件凭证",
                            width: 100,
                            isShow: true,
                            dataField: "voucherNo",
                            needInput: false
                        },
                        {
                            name: "过账错误信息",
                            width: 120,
                            isShow: true,
                            dataField: "sapErrorMsg",
                            needInput: false
                        },
                        {
                            name: "备注",
                            width: 120,
                            isShow: true,
                            dataField: "note",
                            needInput: false
                        }
                    ]
            };

            var btnPermissionCode = {
                sendAdd: window.ActionCode.sendAdd,
                sendEdit: window.ActionCode.sendEdit,
                sendDel: window.ActionCode.sendDel,
                sendExport: window.ActionCode.sendExport,
                dispacth: window.ActionCode.sendAdd,
                sendSign: window.ActionCode.sendSign,
                sendPost: window.ActionCode.sendPost,
                sendGenerate: window.ActionCode.sendGenerate,
                sendIn: window.ActionCode.sendIn,
                sendsyncSettlementPrice: window.ActionCode.sendsyncSettlementPrice,
            };

            $scope.btnPermission = {
                sendAdd: true,
                sendEdit: true,
                sendExport: true,
                sendDel: true,
                dispacth: true,
                sendSign: true,
                sendPost: true,
                sendGenerate: true,
                sendIn: true,
                sendsyncSettlementPrice: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: { left: $scope.tableConfig.fixedWidth + "px" }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        $scope.directPurchasePlan.setFixedWidth();
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };

            $scope.addDispacthBill = function () {
                // 新增发货单
                getDircectPurchasePlanDataList(1);
                $scope.changeTab(3);
            };

            $scope.directPurchasePlan = {
                pageInfo: {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                },
                markInfo: {},
                condition: {},
                dataList: [],
                toolbarConfig: {
                    showAdvanceSearch: false,
                    showColConfig: false,
                },
                tableConfig: {
                    fixedWidth: 120,
                    scrollWidth: 920,
                    tableCol: [
                        {
                            type: "",
                            name: "采购订单号",
                            dataField: "billNo",
                            width: 180,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请单位",
                            dataField: "purchaseOrgName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "供货商",
                            dataField: "supplierOrgName",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "送达方",
                            dataField: "deliveryOrgName",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "备注",
                            dataField: "remark",
                            width: 120,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "",
                            name: "申请时间",
                            dataField: "createDateShow",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: true,
                            sortType: ""
                        },
                        {
                            type: "operate",
                            name: "操作",
                            dataField: "",
                            width: 120,
                            isShow: true,
                            isFixed: true,
                            toSort: false,
                            sortType: ""
                        }
                    ]
                },

                search: function (curPage) {
                    getDircectPurchasePlanDataList(curPage);
                },
                reset: function () {
                    $scope.directPurchasePlan.condition = {};
                },
                switchToolbar: function (toolbar) {
                    if (!!$scope.directPurchasePlan.toolbarConfig["show" + toolbar]) {
                        $scope.directPurchasePlan.toolbarConfig["show" + toolbar] = false;
                    } else {
                        $timeout(function () {
                            $scope.directPurchasePlan.toolbarConfig["show" + toolbar] = true;
                        });
                    }
                },
                setFixedWidth: function () {
                    $scope.directPurchasePlan.tbStyle = {
                        sellFixedWidth: { left: $scope.directPurchasePlan.tableConfig.fixedWidth + "px" }
                    };
                },
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },
                selectRow: function (index) {
                    $scope.directPurchasePlan.markInfo.cueRow = index
                },
                getCheckedListInfo: function () {
                    var ids = [];
                    var items = [];
                    angular.forEach($scope.directPurchasePlan.dataList, function (item) {
                        if (item.isChecked) {
                            ids.push(item.billId);
                            items.push(item);
                        }
                    });
                    return {
                        ids: ids,
                        list: items
                    };
                }
            };

            function getDircectPurchasePlanDataList(curPage) {
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                var param = {};
                param.pageSize = $scope.directPurchasePlan.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.directPurchasePlan.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.directPurchasePlan.pageInfo.curPage;
                param.filters = angular.copy($scope.directPurchasePlan.condition);
                param.filters.seller = true;
                param.filters.sendState = 1;
                param.filters.billStatus = '2';
                param.filters.onlySend = 1;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.sendTimeShow = $filter("YbDate")(item.sendTime, 'yyyy-MM-dd HH:mm:ss');
                        item.isChecked = false;
                    });
                    $scope.directPurchasePlan.pageInfo.totalRows = resp.value.total;
                    $scope.directPurchasePlan.pageInfo.totalPages = resp.value.pages;
                    $scope.directPurchasePlan.dataList = resp.value.list;
                    $scope.markInfo.allCheckedPurchaseBill = false;
                });
            }

            function getDircectPurchasePlanDataInfo(billIds) {
                var param = billIds || [];
                return ybHttp.Post('device', '/purchaseRequest/itemByIds', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            $scope.createDispatchBill = function (planInfo) {
                goToCreateDispacthBillPage([planInfo.billId])
            };

            function goToCreateDispacthBillPage(billIds) {
                $scope.orderObj = {
                    headerInfo: {},
                    materialsList: []
                };
                getDircectPurchasePlanDataInfo(billIds).then(function (data) {
                    if (!data) {
                        return;
                    }
                    var materialsRes = []
                    angular.forEach(data.materialsList, function (item, index) {
                        item.sourceRowNo = item.rowNo;
                        item.totalQty = item.qty;
                        item.qty = item.qty - item.informQty;
                        if (item.qty > 0) {
                            // 过滤掉发货数量为0的数据
                            materialsRes.push(item)
                        }
                    });
                    $scope.orderObj.materialsList = materialsRes;
                    $scope.orderObj.headerInfo.deliveryOrgId = data.deliveryOrgId; // 收货方id
                    $scope.orderObj.headerInfo.deliveryOrgName = data.deliveryOrgName;// 收货方名称
                    $scope.orderObj.headerInfo.applyOrgId = data.purchaseOrgId; // 接收方id
                    $scope.orderObj.headerInfo.applyOrgName = data.purchaseOrgName; // 接收方名字
                    $scope.orderObj.headerInfo.soldOrgId = data.soldOrgId;
                    $scope.orderObj.headerInfo.soldOrgName = data.soldOrgName;


                    $scope.orderObj.headerInfo.contactUser = data.receiverName; // 联系人
                    $scope.orderObj.headerInfo.contactTel = data.receiverTel; // 联系电话
                    $scope.orderObj.headerInfo.address = data.receiverAddress; //地址
                    $scope.orderObj.headerInfo.note = data.remark; // 备注

                    angular.forEach($scope.orderObj.materialsList, function (item, index) {
                        item.rowNo = index + 1;
                    });
                    $scope.changeTab(4);
                });
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.search = function (curpage) {
                getDataList(curpage); // 获取送货单列表
            };

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/sendBill/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.sendTimeShow = $filter("YbDate")(item.sendTime, 'yyyy-MM-dd HH:mm:ss');
                        item.statusStr = $filter("ProgressStatus")(item.status, "inDepot");
                        item.signStr = $filter("ProgressStatus")(item.isSign, "signState");
                        item.deliveryStr = $filter("TrueOrFalse")(item.isDelivery);
                        item.sendTypeStr = item.sendType === 0 ? "普通" : "直投";
                        //add by lqx
                        item.signDateShow = $filter("YbDate")(item.signDate, 'yyyy-MM-dd HH:mm:ss');
                        item.rkDateShow = $filter("YbDate")(item.rkDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.reset = function () {
                $scope.condition = { seller: false };
            };

            $scope.editDispatchBill = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.orderObj.deliveryDate = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd HH:mm:ss');

                    $scope.changeTab(1);
                });
            };

            $scope.delDispatchBill = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/sendBill/remove";
                    var param = [];
                    param.push(item.id);
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search();
                    });
                })
            };

            $scope.dispacth = function (item) {
                var service = "device";
                var reqUrl = "/sendBill/updateIsDelivery";
                var param = {};
                param.id = item.id;
                ybWidget.ShowMessage("确定要发货吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.sign = function (item) {
                var param = {
                    id: item.id
                };

                ybWidget.AuditMsg({
                    title: '确认收货',
                    validateCb: function (val, otherData) {
                        if (otherData.isAbnormal == '1' && !val) {
                            ybWidget.ShowMessage("请输入您的意见", MESG_TYPE.Error);
                            return false;
                        }
                        return true;
                    },
                    passCb: function (val, otherData) {
                        param.isSign = otherData.isAbnormal ? 3 : 1;
                        param.signNote = val;
                        return handleSign(param);
                    },
                    refuseCb: function (val) {
                        param.isSign = 2;
                        param.signNote = val;
                        return handleSign(param);
                    }
                })
            };

            function handleSign(param) {
                return ybHttp.Post('device', '/sendBill/sign', param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            }

            $scope.generate = function (item) {
                var service = "device";
                var reqUrl = "/sendBill/generateOrder";
                var param = {};
                param.id = item.id;
                ybWidget.ShowMessage("确定要生成单据吗？", MESG_TYPE.Ask).then(function (data) {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            function getDetail(item) { // 获取发货单详情
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/sendBill/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.signStr = $filter("ProgressStatus")($scope.orderObj.headerInfo.isSign, "signState");
                    //add by spd
                    if ($scope.orderObj.headerInfo.status == 0) {
                        $scope.orderObj.headerInfo.rkWarehouseCode = '';
                        $scope.orderObj.headerInfo.rkWarehouseDesc = '';
                    }
                    //add by spd end
                    $scope.changeTab(2);
                });
            }

            $scope.postViewDetail = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.changeTab(2);
                });
            };

            $scope.selectAll = function (list, type) { // 选择当前所有的送货单
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                if (type !== 'PurchaseBill') {
                    getBillIds();
                }

            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) { // 单选送货单
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                if (type !== 'PurchaseBill') {
                    getBillIds();
                }
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.batchCreateSendOrder = function () {
                var checkedList = $scope.directPurchasePlan.getCheckedListInfo().list;
                if (checkedList.length === 0) {
                    ybWidget.ShowMessage("您未选择采购单据，请先选择采购单！", MESG_TYPE.Error);
                    return;
                }
                var deliveryOrgId = checkedList[0].deliveryOrgId; // 送达方
                var purchaseOrgId = checkedList[0].purchaseOrgId; // 申请单位

                if (window.XJDQ_ORG_IDs.includes(deliveryOrgId) && checkedList.length > 1) {
                    ybWidget.ShowMessage("送达方为新疆大区，不能批量新增送货单！", MESG_TYPE.Error);
                    return;
                }

                var param = [];
                param.push(checkedList[0].billId);

                for (var i = 1; i < checkedList.length; i++) {
                    var item = checkedList[i];
                    if (item.deliveryOrgId !== deliveryOrgId) {
                        ybWidget.ShowMessage("送达方不一致，不能批量新增送货单！", MESG_TYPE.Error);
                        return;
                    }
                    if (item.purchaseOrgId !== purchaseOrgId) {
                        ybWidget.ShowMessage("申请单位不一致，不能批量新增进货单！", MESG_TYPE.Error);
                        return;
                    }
                    param.push(item.billId);
                }

                goToCreateDispacthBillPage(param);
            };

            $scope.submitDispatchBillData = function (type, invalid) { // 提交新增进货单
                if ($scope.orderObj.materialsList.length === 0) {
                    ybWidget.ShowMessage("至少选择一条零件", MESG_TYPE.Error);
                    return;
                }
                if (isErrorMaterialsQty()) {
                    return;
                }
                var param = angular.copy($scope.orderObj);
                var service = "device";
                var reqUrl = "/sendBill/add";
                if (type === 'update') {
                    reqUrl = "/sendBill/update";
                } else if (type === 'submit') {
                    reqUrl = "/sendBill/submit";
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            function isErrorMaterialsQty() {
                var checkRes = false;
                for (var i = 0; i < $scope.orderObj.materialsList.length; i++) {
                    if ($scope.orderObj.materialsList[i].qtyErr) {
                        checkRes = true;
                        break;
                    }
                }
                return checkRes;
            }

            $scope.cancel = function () { // 取消新增进货单
                $scope.changeTab(0);
            };

            $scope.countTotal = function (item) {  // 送货单数量变化回调
                item.qtyErr = false;
                item.qtyFormatErr = false;
                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyErr = true;
                    item.showQtyErr = true;
                    return;
                }
                if (item.qty > 99999.999) {
                    item.qty = 99999.999;
                }
            };

            $scope.showQtyTip = function (item) {
                if (!!item.qtyErr) {
                    item.showQtyErr = true;
                }
            };
            $scope.hideQtyTip = function (item) {
                item.showQtyErr = false;
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            function initData() {
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    materialsList: [],
                    headerInfo: {}
                };
            }

            $scope.delMateriel = function (item, index, e) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialsList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                    e.stopPropagation();
                    angular.forEach($scope.orderObj.materialsList, function (item, index) {
                        item.rowNo = index + 1;
                    });
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialsList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialsList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialsList[i].isChecked) {
                            $scope.orderObj.materialsList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.materialsList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                    angular.forEach($scope.orderObj.materialsList, function (item, index) {
                        item.rowNo = index + 1;
                    });
                });
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.posting = function (item) {
                item.postingDisabled = true;
                var service = "device";
                var reqUrl = "/sendBill/sapPost";
                var param = {};
                param.id = item.id;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        item.postingDisabled = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDetail(item);
                });
            };

            //打印按钮
            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "SendPrint"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            // 入库
            $scope.inbound = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    if ($scope.isWJ) {
                        if (!$scope.detailInfo.headerInfo.warehouseCode && $scope.detailInfo.headerInfo.rkWarehouseCode) {
                            $scope.detailInfo.headerInfo.warehouseCode = $scope.detailInfo.headerInfo.rkWarehouseCode;
                            $scope.detailInfo.headerInfo.warehouseDesc = $scope.detailInfo.headerInfo.rkWarehouseDesc;
                        }
                    }

                    angular.forEach($scope.detailInfo.materialsList, function(item) {
                        item.currentAmount = Number(ybWidget.Minus(item.qty||0, item.realQty||0));
                        item.currentAmountMax = item.currentAmount
                    });
                    
                    $scope.changeTab(5);
                });
            };

            $scope.checkRequired = function (item, type) {
                if (!item[type] || item[type] == '0') {
                    item[type+"Err"] = true
                    item[type+"ShowErr"] = true
                } else {
                    item[type+"Err"] = false
                    item[type+"ShowErr"] = false
                }
                return item[type+"Err"]
            };

            $scope.showErrTip = function (item, type) {
                if (!!item[type+"Err"]||!!item[type+"ExceedErr"]) {
                    item[type+"ShowErr"] = true
                }
            };

            $scope.hideErrTip = function (item, type) {
                item[type+"ShowErr"] = false
            };

            // 同步价格
            $scope.syncPrice = function (item) {
                var service = "device";
                var reqUrl = "/sendBill/syncSettlementPrice";
                var param = {
                    id: item.id
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                });
            };

            $scope.inboundSubmit = function () {
                if (!$scope.detailInfo.headerInfo.warehouseCode) {
                    ybWidget.ShowMessage('请先选择仓库', MESG_TYPE.Error);
                    return;
                }

                var service = "device";
                var reqUrl = "/warehouseInboundRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var errorCount = 0;
                param.headerInfo.businessOrder = $scope.detailInfo.headerInfo.sendOrder;
                if ($scope.isWJ) {
                    param.headerInfo.warehouseCode = $scope.detailInfo.headerInfo.warehouseCode;
                }
                var warehouseCodeDif = 0;

                angular.forEach($scope.detailInfo.materialsList, function (item) {
                    var listRow = {};
                    listRow.amount = item.amount;
                    listRow.areaCode = item.areaCode;
                    listRow.id = item.id;
                    listRow.locationCode = item.locationCode;
                    listRow.mainId = item.mainId;
                    listRow.materialsDes = item.materialsDes;
                    listRow.materialNo = item.materialsNo;
                    listRow.materialsType = item.materialsType;
                    listRow.note = item.note;
                    listRow.realAmount = item.realAmount;

                    listRow.currentAmount = item.currentAmount;

                    listRow.status = item.status;
                    listRow.unit = item.unit;
                    listRow.warehouseCode = item.warehouseCode;
                    item.locationErr = false;
                    if ((item.status === 0 || item.status === 1) && !item.locationCode) {
                        item.locationErr = true;
                        errorCount++;
                    }

                    if (item.currentAmountMax != 0 && $scope.checkRequired(item, 'currentAmount')) {
                        errorCount++;
                    }

                    param.detailList.push(listRow);
                    if ($scope.isWJ) {
                        if (item.warehouseCode && item.warehouseCode != '') {
                            if (param.headerInfo.warehouseCode != item.warehouseCode) {
                                warehouseCodeDif = 1;
                            }
                        }
                    }
                });
                if (errorCount > 0) {
                    return;
                }
                //
                if ($scope.isWJ) {
                    if (warehouseCodeDif == 1) {
                        ybWidget.ShowMessage('所选储位和仓库不匹配', MESG_TYPE.Error);
                        return;
                    }
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.selDepot = function (item) {
                if (!$scope.detailInfo.headerInfo.warehouseCode) {
                    ybWidget.ShowMessage('请先选择仓库', MESG_TYPE.Error);
                    return;
                }
                var param = {
                    warehouseCode: $scope.detailInfo.headerInfo.warehouseCode
                };

                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };

            // 选择仓库
            $scope.selectWarehouse = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    $scope.detailInfo.headerInfo.warehouseCode = data.warehouseCode;
                    $scope.detailInfo.headerInfo.warehouseDesc = data.description;
                    //
                    if ($scope.isWJ) {

                        var param = {
                            id: $scope.detailInfo.headerInfo.id,
                            warehouseCode: data.warehouseCode
                        };
                        ybHttp.Get('device', '/sendBill/getMaterialLocation', param).then(function (resp) {
                            if (resp.code !== 0) {
                                // ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                return;
                            }
                            let mapLoaction = resp.value;
                            if (mapLoaction) {
                                angular.forEach($scope.detailInfo.materialsList, function (item) {
                                    // 
                                    item.locationCode = null;
                                    item.areaCode = null;
                                    item.warehouseCode = null;
                                    if (mapLoaction[item.materialsNo]) {
                                        let location = mapLoaction[item.materialsNo]
                                        item.locationCode = location.locationCode;
                                        item.areaCode = location.areaCode;
                                        item.warehouseCode = location.warehouseCode;
                                    }
                                });
                            } else {
                                angular.forEach($scope.detailInfo.materialsList, function (item) {
                                    item.locationCode = null;
                                    item.areaCode = null;
                                    item.warehouseCode = null;
                                });
                            }
                        });

                    }
                })
            };

            // 入库时清除仓库
            $scope.clearWarehouse = function () {
                $scope.detailInfo.headerInfo.warehouseCode = null;
            };

            $scope.importData = function () {
                var param = {
                    name: "钢印号",
                    templateReqService: "device",
                    templateReqUrl: "/sendBill/downloadSteelNoExcel",
                    importReqService: "device",
                    importReqUrl: "/sendBill/importSteelNoExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);

                if ($scope.needHide) {
                    $scope.tableConfig.tableCol = ybWidget.HideTableCols($scope.tableConfig.tableCol, ['signStr', 'signDateShow']);
                }
            })();
        }])
        ;
})(window, window.angular);
